package com.blockchain.service.impl;


import com.blockchain.service.EmailService;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@Service
public class EmailServiceImpl implements EmailService {

    private final JavaMailSender mailSender;
    //存储手机号与验证码之间的映射关系
    private final Map<String,String> emailCaptcha=new ConcurrentHashMap<>();
    @Autowired
    public EmailServiceImpl(JavaMailSender mailSender){
        this.mailSender=mailSender;
    }
    @Value("${spring.mail.username}")
    private String username;
    @Override
    public void sendEmail(String email) {
        try {
            MimeMessage message=mailSender.createMimeMessage();
            MimeMessageHelper helper=new MimeMessageHelper(message,true);
            helper.setTo(email);
            helper.setSubject("邮箱验证码");
            String captcha=getCaptcha(email);
            helper.setText("您的验证码是"+captcha+"，该验证码5分钟内有效，请勿泄露他人。");
            helper.setFrom(username);
            mailSender.send(message);
            storeCaptcha(email,captcha);
        }catch (MessagingException e){
            e.printStackTrace();
        }
    }
    //存储验证码
    public void storeCaptcha(String email,String captcha){
        emailCaptcha.put(email,captcha);
        //设置验证码的过期时间
        ScheduledExecutorService scheduledExecutorService= Executors.newScheduledThreadPool(1);
        scheduledExecutorService.schedule(()->{
            emailCaptcha.remove(email);
        },5,TimeUnit.MINUTES);
    }
    @Override
    public String getCaptcha(String email){

        return emailCaptcha.get(email);
    }
}